<template>
  <div class="editable-table">
    <el-table
      v-if="tableData"
      :data="tableData"
      border
      v-loading="loading"
      @cell-click="handleCellClick"
    >
      <el-table-column
        v-for="(t, n) in columns"
        :key="n"
        :prop="t.fields"
        :label="t.translate"
        align="center"
      >
        <template slot-scope="{ row, column, $index }">
          <div>
            <el-input
              v-if="
                t.isEdit &&
                editingIndex === $index &&
                column.property === editProperty
              "
              v-model="row[t.fields]"
              ref="editableInput"
              clearable
              @blur="saveEdit(row, $index)"
              @keydown.enter="saveEdit(row, $index)"
            ></el-input>
            <span v-else>{{ row[t.fields] }}</span>
            <div
              v-if="
                editErrorIndex === $index && column.property === editProperty
              "
              class="error-message"
            >
              值不能为空
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "EditableTable",
  props: {
    tableData: {
      type: Array,
    },
    columns: {
      type: Array,
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      editingIndex: null,
      editProperty: null,
      editErrorIndex: null,
    };
  },
  methods: {
    handleCellClick(row, column) {
      const rowIndex = this.tableData.indexOf(row);
      this.editingIndex = rowIndex;
      this.editProperty = column.property;
      this.$nextTick(() => {
        if (this.$refs.editableInput && this.$refs.editableInput[0]) {
          this.$refs.editableInput[0].focus();
        }
      });
    },
    saveEdit(row) {
      if (row[this.editProperty] == null || row[this.editProperty] === "") {
        this.editErrorIndex = this.editingIndex;
        return;
      }
      this.$emit("edit-save", row);
      this.editingIndex = null;
      this.editProperty = null;
      this.editErrorIndex = null;
    },
  },
};
</script>

<style lang="scss" scoped>
.error-message {
  color: red;
  font-size: 12px;
  margin-top: 4px;
}
</style>
